<template>
  <!-- 
        1, 当我们点击 “新增车辆信息” 按钮时，通过一个开关判断表单内容是否全部填写了，若全部填写了则添加一个新的表单，
            反之提醒用户完善信息；
        2, 当我们点击 “删除此条车辆信息” 按钮时，通过拿到的当前下标再配合splice方法实现删除表单。
    -->
  <div class="addFormBox">
    <div v-for="(item, index) in form" :key="index">
      <div class="formBox">
        <div class="formCotant">
          <h3>车辆信息 {{ index + 1 }}</h3>
          <!-- 表单内容 -->
          <el-form label-width="80px">
            <el-form-item label="车牌号" :rules="[{ required: true, message: '车牌号不能为空', trigger: ['blur','change']} ]">
              <el-input v-model="item.carBoard"></el-input>
            </el-form-item>
            <el-form-item label="车牌颜色">
              <el-input v-model="item.carColor"></el-input>
            </el-form-item>
            <el-form-item label="排放阶段">
              <el-input v-model="item.discharge"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- 操作按钮 -->
        <div>
          <el-button @click="submitForm" type="primary">发布信息</el-button>
          <el-button @click="addForm" type="success">添加车辆信息</el-button>
          <el-button @click="removeIdx(index)" type="danger">删除此条车辆信息</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单绑定的数据
      form: [
        {
          carBoard: "",
          carColor: "",
          discharge: "",
        },
      ],
    };
  },
  methods: {
    // 添加操作
    addForm() {
      // 定义一个开关判断是否能添加信息
      let status = true;
      this.form.forEach((item) => {
        if (item.carBoard == "" || item.carColor == "" || item.discharge == "") {
            this.msgTips('notAdd');
            status = false;
        }
      });
      if(status) {
        this.form.push({
          carBoard: "",
          carColor: "",
          discharge: "",
        })
      }
    },
    // 删除操作
    removeIdx(index) {
        this.form.splice(index, 1);
        this.msgTips('removeOk')
    },
    // 发布操作
    submitForm() {
        const forms = [{...this.carBoard}, {...this.carColor}, {...this.discharge}]
        console.log(forms);
    },
    msgTips(msg) {
      let message;
      let type;
      if(msg == 'notAdd') {
        message = '请完善信息后在添加！';
        type = 'warning';
      } else if(msg == 'removeOk') {
        message = '删除信息成功';
        type = 'success';
      }
      this.$message({
        message,
        type,
      })
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
  width: 320px;
}

.addFormBox {
  margin: 20px;
}

.formBox {
  margin-bottom: 20px;
  padding: 30px 40px;
  background: white;
  border-radius: 30px;
}

h3 {
  margin: 0px 0px 20px 0px;
}
</style>
